import { reactive, ref } from 'vue'
import { ElMessage } from 'element-plus'
import {
  listAllApi,
  listAllWithStationApi,
  queryInitApi,
  toggleApi,
  listApi,
  enablePipelineApi,
  changeCycleApi,
  updateInfoApi
} from '../api/pipeline'
import { useTemperature } from './useTemperature'
import { useFlow } from './useFlow'
import { useTotalFlow } from './useTotalFlow'
import { useStatus } from './useStatus'
const { clearAllTemperatureData } = useTemperature()
const { clearAllFlowData } = useFlow()
const { currentPipelineId } = useTotalFlow()
const { lightMap } = useStatus()

const currentPipeline = ref()
const pipelines = ref([])
const pipelineS = ref([])
const pipelineList = reactive({
  arr: []
})
const searchPipelineId = ref()
const pipelineListLoading = ref(true)
const pipelineSearchForm = reactive({})
const currentPage = ref(1)
const pageSize = ref(7)
const total = ref(0)
const editCycleVisible = ref(false)
const cycle = ref({})
const editPipelineForm = reactive({})
const editPipelineVisible = ref(false)

async function queryInitPipeline() {
  const { data: res } = await queryInitApi()
  currentPipeline.value = res.data.name
}
async function listAllPipeline() {
  const { data: res } = await listAllApi()
  pipelines.value = res.data.map((item) => {
    return {
      id: item.id,
      label: item.name,
      value: item.name,
      disabled: item.status !== 1
    }
  })
}
async function togglePipeline() {
  const { data: res } = await toggleApi(currentPipeline.value)
  if (res.success) {
    // 更新总流量的颜色
    for (let i = 0; i < pipelines.value.length; i++) {
      if (pipelines.value[i].label === currentPipeline.value) {
        currentPipelineId.value = pipelines.value[i].id
      }
    }
    clearAllTemperatureData()
    clearAllFlowData()
    ElMessage.success(res.data)
  }
}
async function getPipelinesWithStation() {
  const { data: res } = await listAllWithStationApi()
  if (res.success) {
    searchPipelineId.value = res.map.defaultPipelineId
    pipelineS.value = res.data.map((item) => {
      return {
        id: item.station.id,
        name: item.station.name,
        pipelines: item.pipelines.map((pipeline) => {
          return {
            id: pipeline.id,
            name: pipeline.name
          }
        })
      }
    })
  }
}
async function getPipelineList() {
  pipelineListLoading.value = true
  const { data: res } = await listApi(pipelineSearchForm, currentPage.value, pageSize.value)
  pipelineList.arr = res.data.records
  total.value = res.data.total
  setTimeout(() => {
    pipelineListLoading.value = false
  }, 500)
}
async function enablePipeline(pipelineId, status) {
  const { data: res } = await enablePipelineApi(pipelineId, status ^ 1)
  if (!res.success) {
    ElMessage.error({
      message: res.msg,
      dangerouslyUseHTMLString: true
    })
    return
  }
  for (const pipeline of pipelineList.arr) {
    if (pipeline.id === pipelineId) {
      pipeline.status = pipeline.status ^ 1
      const light = lightMap.get(pipelineId)
      if (light) {
        if (pipeline.status === 0) {
          light.disable = true
          light.danger = false
        } else {
          light.health = true
        }
      }
      break
    }
  }
  ElMessage.success(res.data)
}
async function editCycle() {
  const period = cycle.value.hour * 3600 + cycle.value.minute * 60 + cycle.value.second
  const { data: res } = await changeCycleApi(cycle.value.pipelineId, period)
  if (!res.success) {
    ElMessage.error({
      message: res.msg,
      dangerouslyUseHTMLString: true
    })
    return
  }
  editCycleVisible.value = false
  ElMessage.success(res.data)
  getPipelineList()
}
async function editPipeline() {
  const { data: res } = await updateInfoApi(editPipelineForm)
  if (!res.success) {
    ElMessage.error({
      message: res.msg,
      dangerouslyUseHTMLString: true
    })
    return
  }
  getPipelineList()
  ElMessage.success(res.data)
  editPipelineVisible.value = false
}

function preEditPipeline(pipeline) {
  Object.assign(editPipelineForm, pipeline)
  editPipelineVisible.value = true
}
function calculateCycle(data) {
  const r = parseCycle(data)
  let res = ''
  if (r.hour > 0) {
    res += r.hour + '小时'
  }
  if (r.minute > 0) {
    res += r.minute + '分'
  }
  if (r.second > 0) {
    res += r.second + '秒'
  }
  return res
}
function preEidtCycle(pipeline) {
  const r = parseCycle(pipeline.cycle)
  cycle.value.hour = r.hour
  cycle.value.minute = r.minute
  cycle.value.second = r.second
  cycle.value.pipelineId = pipeline.id
  editCycleVisible.value = true
}
function parseCycle(data) {
  return {
    hour: Math.floor(data / 3600),
    minute: Math.floor((data % 3600) / 60),
    second: data % 60
  }
}

export const usePipeline = () => {
  return {
    currentPipeline,
    pipelines,
    pipelineS,
    pipelineList,
    searchPipelineId,
    pipelineListLoading,
    pipelineSearchForm,
    currentPage,
    pageSize,
    total,
    editCycleVisible,
    cycle,
    editPipelineForm,
    editPipelineVisible,
    queryInitPipeline,
    listAllPipeline,
    getPipelinesWithStation,
    togglePipeline,
    getPipelineList,
    enablePipeline,
    calculateCycle,
    preEidtCycle,
    editCycle,
    preEditPipeline,
    editPipeline
  }
}
